package com.example.business.service.impl;

import com.example.business.dao.dto.ArticleDTO;
import com.example.business.dao.entity.Article;
import com.example.business.dao.entity.ArticleDetails;
import com.example.business.dao.mapper.ArticleDetailsMapper;
import com.example.business.dao.mapper.ArticleMapper;
import com.example.business.service.ArticleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ArticleServiceImpl implements ArticleService {
    private final ArticleMapper articleMapper;
    private final ArticleDetailsMapper articleDetailsMapper;

    @Override
    public ArticleDTO getArticle() {
        try {
            // 查询最新的1篇文章
            List<Article> articles = articleMapper.selectLatestArticles(1);
            if (articles.isEmpty()) {
                throw new RuntimeException("获取推荐文章失败"); // 返回空对象
            }

            Article article = articles.get(0);
            // 查询文章详情（取前200字作为摘要）
            ArticleDetails details = articleDetailsMapper.selectByArticleId(article.getId());
            String summary = details != null ? details.getContent() : "";
            if (summary.length() > 200) {
                summary = summary.substring(0, 200) + "...";
            }

            // 封装DTO（包含ID、标题、摘要）
            ArticleDTO dto = new ArticleDTO();
            dto.setId(article.getId()); // 关键：返回文章ID
            dto.setTitle(article.getTitle());
            dto.setSummary(summary);
            return dto;
        } catch (Exception e) {
            log.error("获取推荐文章失败", e);
            throw new RuntimeException("获取推荐文章失败");
        }

    }
}
